// Copyright (C) 2023 Ant Group CO., Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fs::File;
use std::io::{Result, Write};
use std::path::PathBuf;
use std::process::Command;

fn main() -> Result<()> {
    gen_vector_asm()?;
    build_trust_lib();
    Ok(())
}

/// Generate assembly file for x86_64 trap vector
fn gen_vector_asm() -> Result<()> {
    let out_path = PathBuf::from(std::env::var("OUT_DIR").unwrap());
    let mut f = File::create(out_path.join("exception.S"))?;

    writeln!(f, "# generated by build.rs - do not edit")?;
    writeln!(f, ".section .text")?;
    for i in 0..256 {
        writeln!(f, "__entry{}:", i)?;
        if !(i == 8 || (10..=14).contains(&i) || i == 17) {
            writeln!(f, "\tpush 0")?;
        }
        writeln!(f, "\tpush {}", i)?;
        writeln!(f, "\tjmp common_exception_entry")?;
    }

    writeln!(f, "\n.section .rodata")?;
    writeln!(f, ".global exception_entries")?;
    writeln!(f, "exception_entries:")?;
    for i in 0..256 {
        writeln!(f, "\t.quad __entry{}", i)?;
    }
    Ok(())
}

fn build_trust_lib() {
    Command::new("make").args(&["-C", "lib"]).status().unwrap();
    println!("cargo:rustc-link-search=native=lib");
    println!("cargo:rustc-link-lib=static=tpm");
}
